﻿<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:variable name="name" select="//body//h1[1]" />

  <xsl:variable name="images" as="element()*">
      <xsl:for-each select="//body//img[@src]">
        <xsl:element name="image">
          <xsl:attribute name="src">
            <xsl:value-of select="@src"/>
          </xsl:attribute>
          <xsl:if test="@alt">
            <xsl:attribute name="alternate">
              <xsl:value-of select="@alt"/>
            </xsl:attribute>
          </xsl:if>
        </xsl:element>
        
      </xsl:for-each>
  </xsl:variable>
  <xsl:template match="/html">
    <article>
      <xsl:element name="meta">
        <xsl:if test="body//h1">
          <xsl:attribute name="name">
            <xsl:value-of select="$name"/>
          </xsl:attribute>
        </xsl:if>
      </xsl:element>
      <content>
        <xsl:apply-templates />
      </content>
      <images>
        <xsl:copy-of select="$images" />
      </images>
      <files>
        <xsl:for-each select="./body/*[matches(., '\[#file .*\]', 'i')]">
          <xsl:analyze-string select="." regex="\[#file (.*)\](.*)" flags="i">
            <xsl:matching-substring>
              <xsl:element name="file">
                <xsl:attribute name="src">
                  <xsl:value-of select="regex-group(1)"/>
                </xsl:attribute>
                <xsl:attribute name="name">
                  <xsl:value-of select="normalize-space(regex-group(2))"/>
                </xsl:attribute>
              </xsl:element>
            </xsl:matching-substring>
          </xsl:analyze-string>
        </xsl:for-each>
      </files>
    </article>
  </xsl:template>
  <xsl:template match="head">
  </xsl:template>

  <xsl:template match="p">
    <p>
      <xsl:apply-templates/>
    </p>
  </xsl:template>
  <xsl:template match="h1|h2|h3|h4|h5|h6">
    <xsl:if test="not(. = $name)">
      <xsl:element name="{name()}">
        <xsl:apply-templates />
      </xsl:element>
    </xsl:if>
  </xsl:template>
  <xsl:template match="//body//*[@class = 'MsoIntenseQuote' or @class = 'quot' or @class = 'citace']">
    <xsl:element name="quote">
      <xsl:apply-templates />
    </xsl:element>
  </xsl:template>
  <xsl:template match="text()">
    <xsl:choose>
      <xsl:when test="matches(., '\[#file .*\]', 'i')">
        <xsl:analyze-string select="." regex="\[#file (.*)\](.*)" flags="i">
          <xsl:matching-substring>
            <file src="{regex-group(1)}" name="{regex-group(2)}"></file>
          </xsl:matching-substring>
        </xsl:analyze-string>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="." />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>
